package com.tarena.luban.demo.rocket.controller;

import com.tarena.luban.demo.rocket.bean.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class HelloController {
    /**
     * 测试消息的发送
     */
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping("/hello/sync")
    public String sendHelloSync(String msg){
        //将消息同步发送
        log.info("进入消息发送的代码,即将发送消息:{}",msg);
        /**
         * 至少传递2个参数
         * String desitination 主题名称+tags值
         * Message message spring封装的一层message对象
         */
        //payLoad 载荷 携带的消息内容,会对传递的载荷进行序列化,然后才会发送消息到队列
        Message<String> message = MessageBuilder.withPayload(msg).build();
        SendResult sendResult = rocketMQTemplate.syncSend("rocket-topic-01:tag1", message);
        log.info("queue info:{}",sendResult.getMessageQueue().toString());
        log.info("send result:{}",sendResult.getSendStatus());
        return "success";
    }
    @GetMapping("/hello/async")
    public String sendHelloAsync(String msg){
        log.info("进入消息发送的代码,即将发送消息:{}",msg);
        Message<String> message = MessageBuilder.withPayload(msg).build();
        rocketMQTemplate.asyncSend("rocket-topic-01", message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("成功发送了消息");
            }
            @Override
            public void onException(Throwable throwable) {
                log.info("发送消息异常",throwable);
            }
        });
        return "success";
    }
    @GetMapping("/hello/user")
    public String sendUser(String msg){
        //发送一个user对象到rocketmq
        User user=new User();
        user.setUsername("王翠花");
        user.setAge(18);
        user.setMsg(msg);
        Message<User> message = MessageBuilder.withPayload(user).build();
        rocketMQTemplate.syncSend("rocket-topic-02",message);
        return "success";
    }
}
